﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataConDemoWebRole.Business;
using System.Diagnostics;

namespace DataConDemoWebRole.Controllers
{
    /// <summary>
    /// This controller provides tiles in a form suitable for use by Bing Maps controls.
    /// </summary>
    public class TileController : Controller
    {
        /// <summary>
        /// Get the tile for a given layer and quadkey.
        /// </summary>
        /// <remarks>
        /// Cache the results since the data doesn't change. Here I used 3600 seconds (1 hour).
        /// Change to 10 seconds or less to observe the results of not caching as you move the map around.
        /// If a tile cannot be produced, it is best to return 404 immediately so the map will not try to show it.
        /// </remarks>
        /// <param name="layer">name of layer e.g. Countries</param>
        /// <param name="quadkey">key of tile</param>
        /// <returns>an image in a stream</returns>
        [OutputCache(Duration = 3600, VaryByParam = "*")]
        public ActionResult Get(string layer, string quadkey, bool thematic)
        {
            try
            {
                Debug.WriteLine("Tile starting " + layer + ", " + quadkey);
                var ds = new DataService();
                var tm = new TileMaker(ds);
                var stream = tm.GetTile(layer, quadkey, thematic);
                Debug.WriteLine("Tile finished " + layer + ", " + quadkey);
                return File(stream, "image/png");
            }
            catch
            {
            }
            Debug.WriteLine("Tile not found " + layer + ", " + quadkey);
            return new HttpStatusCodeResult(404, "Tile not found");
        }
    }

    // This class returns a 404 message.
    // This class is present in MVC3. 
    // This version was stolen from http://dotnet.dzone.com/news/aspnet-mvc-3-creating
    public class HttpStatusCodeResult : ViewResult
    {
        private int _statusCode;
        private string _description;

        public HttpStatusCodeResult(int statusCode,
               string description = null)
        {
            _statusCode = statusCode;
            _description = description;

        }

        public override void ExecuteResult(ControllerContext context)
        {
            var httpContext = context.HttpContext;
            var response = httpContext.Response;

            response.StatusCode = _statusCode;
            response.StatusDescription = _description;
        }
    }

}
